package com.atguigu.yygh.cmn.service.impl;

import com.atguigu.yygh.cmn.mapper.DictMapper;
import com.atguigu.yygh.cmn.service.DictService;
import com.atguigu.yygh.model.cmn.Dict;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * @author study
 * @version 1.0
 * @date 2021/5/6 15:51
 */
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    @Override
    public List<Dict> findChildData(Long id) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", id);
        final List<Dict> dicts = baseMapper.selectList(wrapper);
        dicts.forEach(dict -> {
            dict.setHasChildren(isChildren(dict.getId()));
        });
        return dicts;
    }

    //判断是否有子节点
    private boolean isChildren(Long id) {
        final Integer count = baseMapper.selectCount(new QueryWrapper<Dict>().eq("parent_id", id));
        return count > 0;
    }

    @Override
    public String getDicName(String dictCode, String value) {
        if (StringUtils.isEmpty(dictCode)) {
            QueryWrapper<Dict> wrapper = new QueryWrapper<>();
            wrapper.eq("value", value);
            final Dict dict = baseMapper.selectOne(wrapper);
            return dict.getName();
        }

        //根据dictCode查询
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("dict_code", dictCode);
        final Dict codeDict = baseMapper.selectOne(wrapper);

        final Long parentID = codeDict.getId();
        //根据parentID
        final Dict finalDict = baseMapper.selectOne(new QueryWrapper<Dict>().eq("parent_id", parentID).eq("value", value));
        return finalDict.getName();
    }

}
